﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace cludg.Services.Security
{
    using Domain.Users;
    using Repository.Security;

    public class Membership : IMembership
    {
        private readonly User _anonymouse = new User() { Id = null, DisplayName = "Anonymouse", Role = UserRole.Anonymouse };

        protected readonly ISecurityRepository Repository;

        public Membership(ISecurityRepository repository)
        {
            Repository = repository;
            RegisterValidateUserStrategies();
        }

        public User Anonymouse { get { return _anonymouse; } }

        public User GetUser(string userId)
        {
            return Repository.GetUserById(userId);
        }

		public User GetUserByName(string userName)
		{
			return Repository.AllUsers.FirstOrDefault(x => x.UniqueName == userName);
		}

        #region Validate user strategies
        private readonly IList<ValidateUserStrategy> ValidateUserStrategies = new List<ValidateUserStrategy>();

        internal void RegisterValidateUserStrategy(ValidateUserStrategy strategy)
        {
            ValidateUserStrategies.Add(strategy);
        }

        protected virtual void RegisterValidateUserStrategies()
        {
            RegisterValidateUserStrategy(new ValidateUserStrategies.LoginPassword());
            RegisterValidateUserStrategy(new ValidateUserStrategies.ThirdParty());
        }

        internal virtual ValidateUserStrategy GetValidateUserStrategy(Principal principal)
        {
            return ValidateUserStrategies.FirstOrDefault(s => s.IsForPrincipal(principal));
        } 
        #endregion

        #region Users validation
        public string ValidateUser(Principal principal)
        {
            var strategy = GetValidateUserStrategy(principal);

            System.Diagnostics.Debug.Assert(strategy != null);

            return strategy.ValidateUser(Repository, principal);
        }
        #endregion
    }
}
